#include "config.h"

#include "ecm.h"

#include <windows.h>

#define ENVIRON_PATH	"System\\CurrentControlSet\\Control\\Session Manager\\Environment"

static ECMBOOL
SetEnv(const char *name, const char *value)
{
	HKEY	hkey;
	DWORD	cbData;
	ECMBOOL	res = ECM_FALSE;

	cbData = 1024;
	if (RegOpenKey(HKEY_LOCAL_MACHINE, ENVIRON_PATH, &hkey) != ERROR_SUCCESS)
		return ECM_FALSE;

	if (!ecm_empty_str(value)) {
		if (RegSetValueEx(hkey, name, 0, REG_SZ, (const BYTE *)value, ecm_strlen(value)) != ERROR_SUCCESS)
			goto out;
	}
	else {
		if (RegDeleteValue(hkey, name) != ERROR_SUCCESS)
			goto out;
	}
	res = ECM_TRUE;
out:
	RegCloseKey(hkey);
	return ECM_TRUE;
}

ECMBOOL
parse_name_value(const char *c_cmdline, char **pname, char **pvalue)
{
	char	*cmdline, *equal;
	char	*name, *value;
	ECMBOOL	res = ECM_FALSE;

	if (c_cmdline == NULL)
		return FALSE;
	name = cmdline = _strdup(c_cmdline);
	equal = strchr(cmdline, '=');
	if (equal == NULL)
		goto out;
        *equal = '\0';
	value = equal + 1;
	if (*value == '\"') {
		char	*q;

		value++;
		if ((q = strchr(value + 1, '\"')) == NULL)
			goto out;
		*q = '\0';
	}
	if (name == NULL)
		goto out;
	*pname = _strdup(name);
	*pvalue = _strdup(value);
	res = ECM_TRUE;
out:
	free(cmdline);
	return res;
}

int APIENTRY
WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	char	*name, *value;

	if (!parse_name_value(lpCmdLine, &name, &value)) {
		MessageBox(NULL, "setenv <name>=<value>", "Usage", MB_OK);
		return 1;
	}
	if (SetEnv(name, value)) {
		char	result[1024]; /* TODO: */
		SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, (LPARAM)"Environment", SMTO_ABORTIFHUNG, 5000, (PDWORD_PTR)result);
	}
	free(name);
	free(value);
	return 0;
}
